//
//  RHEndpointListVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/5/16.
//

#import "RHEndpointListVC.h"
#import "RHEndpointListCell.h"
#import "RHEndPointModel.h"
#import "NSMutableDictionary+Ordered.h"
#import "RHDataMonitor233VC.h"
#import "RHDataMonitorMe61VC.h"
#import "RHDataMonitorMe215VC.h"
#import "RHDeviceInverterDataVC.h"

@interface RHEndpointListVC ()<UITableViewDelegate,UITableViewDataSource>
//数据源
@property (nonatomic, strong) NSMutableArray *endpointListArr;

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic, assign) RequestType requestType;
//当前页数
@property (nonatomic, assign) NSInteger currentPage;
//总页数
@property (nonatomic, assign) NSInteger totalPage;
//每页多少条数据
@property (nonatomic, assign) NSInteger numOfPage;

@property (nonatomic ,copy) NSString *keyCode;
@end

@implementation RHEndpointListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:CFTabViewBgColor];
    self.currentPage = 1;
    self.numOfPage = 10;
    self.requestType = RequestTypeRefresh;
    [self setupUI];
    [self getEndpointList];
}

- (void)setupUI{
    kWeakSelf;
   
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHEndpointListCell class] forCellReuseIdentifier:@"RHEndpointListCell"];
   
    [self.view addSubview:_tableView];
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_offset(0);
        make.top.mas_offset(0);
    }];
   
    [_tableView addHeaderRefresh:^{
        [weakSelf.tableView.mj_footer resetNoMoreData];
        weakSelf.requestType = RequestTypeRefresh;
        weakSelf.currentPage = 1;
        weakSelf.keyCode = @"";
        [weakSelf getEndpointList];
       
    }];
    
    [_tableView addBackFooterRefresh:^{
        weakSelf.requestType = RequestTypeAdd;
        weakSelf.currentPage++;
        [weakSelf getEndpointList];
    }];
}

#pragma mark ------- action ----------

-(void)searchDeviceWithKeyCode:(NSString*)keyCode
{
    self.currentPage = 1;
    self.requestType = RequestTypeRefresh;
    [self.tableView endFooterResetNoMoreData];
    self.keyCode = keyCode;
    [self getEndpointList];
}

-(void)getEndpointList
{
    NSDictionary *para = @{@"pageNum":@(self.currentPage),
                           @"pageSize":@(self.numOfPage),
                           @"groupName":ValidNullData(self.keyCode),
                           @"endpointCode":ValidNullData(self.endpointCode),
                           @"deviceId":ValidNullData(self.keyCode),
                           @"stateList":ValidNullData(self.filterDic[@"deviceStatus"]),
                           @"workStateList":ValidNullData(self.filterDic[@"runStatus"])
    };
    para = [NSMutableDictionary removeNullValue:para];
    [QMUITips showLoadingInView:self.view];
   [RHEndPointModel startGetWithCompletionAPIKey:H_getAllEndpointList argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
       [self.tableView endHeaderRefresh];
       if (resultModel.code == 200||resultModel.code == 0) {
           NSInteger total = [request.responseObject[@"total"] integerValue];
           self.totalPage = total%self.numOfPage? total/self.numOfPage+1 : total/self.numOfPage;
           NSMutableArray *arr = [NSMutableArray arrayWithArray:resultModel.data];
           //下拉刷新
           if(self.requestType == RequestTypeRefresh){
               [self.tableView endHeaderRefresh];
               self.endpointListArr = arr;
           }else{//上拉加载
               [self.tableView endFooterRefresh];
               [self.endpointListArr addObjectsFromArray:arr];
           }
           if(self.currentPage >= self.totalPage){
               [self.tableView endFooterRefreshWithNoMoreData];
           }
           [self.tableView reloadData];
           if(self.endpointListArr.count == 0){
               [self.tableView endFooterRefreshWithNoMoreData];
           }
       }
   } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
       [self.tableView endHeaderRefresh];
   }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.endpointListArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHEndpointListCell *cell= [tableView dequeueReusableCellWithIdentifier:@"RHEndpointListCell"];
    cell.endpointModel = [self.endpointListArr safeObjectAtIndex:indexPath.row];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    RHEndPointModel *endpointModel = [self.endpointListArr safeObjectAtIndex:indexPath.row];
    
    [self getEndPointRerationWithEndpointModel:endpointModel];
    
    
    
    
}

#pragma mark ----- 获取设备节点关系 -------
- (void)getEndPointRerationWithEndpointModel:(RHEndPointModel*)endpointModel
{
    [QMUITips showLoadingInView:self.view];
    NSString *url = [NSString stringWithFormat:@"%@/%@",H_getDevRelationTypeList,endpointModel.deviceId];
    [RHEndPointTypeModel startGetWithCompletionAPIKey:url argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            
            NSArray *typeArr = resultModel.data;
            __block RHEndPointTypeModel *endpointTypeModel;
            __block RHEndPointModel *sub_endpointModel;
            [typeArr enumerateObjectsUsingBlock:^(RHEndPointTypeModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj.endpointTypeCode isEqualToString:endpointModel.endpointCode]) {
                    endpointTypeModel = obj;
                }
                [obj.nodes enumerateObjectsUsingBlock:^(RHEndPointModel * _Nonnull obj2, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (obj2.endpointId == endpointModel.endpointId) {
                        sub_endpointModel = obj2;
                    }
                }];
            }];
       
            
            if (!endpointTypeModel) {
                return;
            }
            
            NSDictionary *dic = [endpointModel yy_modelToJSONObject];
//            RHEndPointTypeModel *typeModel = [RHEndPointTypeModel yy_modelWithJSON:dic];
//            typeModel.endpointTypeId = endpointTypeModel.endpointTypeId;
//            typeModel.endpointTypeCode = endpointModel.endpointCode;
            endpointTypeModel.nodes = @[sub_endpointModel];
            RHDeviceModel *deviceModel = [RHDeviceModel yy_modelWithJSON:dic];
            deviceModel.device_id = endpointModel.deviceInfoId.integerValue;
            
            //233k
            if ([endpointModel.deviceTypeCode is233DeviceType]) {
                RHDataMonitor233VC *monitorVC = [[RHDataMonitor233VC alloc]initWithEndpointModel:sub_endpointModel];
                monitorVC.curDevModel = deviceModel;
                monitorVC.endPointTypeModel = endpointTypeModel;
                monitorVC.updateDevStatus = ^{
        //            [weakSelf getDeviceStatus];
        //            [weakSelf getModueStatus];
                };
                [self.navigationController pushViewController:monitorVC animated:YES];
            }else
            
            //61度电
            if ([endpointModel.deviceTypeCode is61DeviceType]) {
                RHDataMonitorMe61VC *monitorVC = [[RHDataMonitorMe61VC alloc]initWithEndpointModel:sub_endpointModel];
                monitorVC.curDevModel = deviceModel;
                monitorVC.endPointTypeModel = endpointTypeModel;
                monitorVC.updateDevStatus = ^{
        //            [weakSelf getDeviceStatus];
        //            [weakSelf getModueStatus];
                };
                [self.navigationController pushViewController:monitorVC animated:YES];
            }else
            
            //215k
            if ([endpointModel.deviceTypeCode isEqualToString:R_EC215100D0]) {
                RHDataMonitorMe215VC *monitorVC = [[RHDataMonitorMe215VC alloc]initWithEndpointModel:sub_endpointModel];
                monitorVC.curDevModel = deviceModel;
                monitorVC.endPointTypeModel = endpointTypeModel;
                monitorVC.updateDevStatus = ^{
        //            [weakSelf getDeviceStatus];
        //            [weakSelf getModueStatus];
                };
                [self.navigationController pushViewController:monitorVC animated:YES];
            }else{
                
                //户用 , 一体机
                RHDeviceInverterDataVC *inverterVC = [[RHDeviceInverterDataVC alloc]initWithEndpointModel:sub_endpointModel];
                inverterVC.curDevModel = deviceModel;
                inverterVC.endPointTypeModel = endpointTypeModel;
                inverterVC.updateDevStatus = ^{
            //        [weakSelf getDeviceStatus];
            //        [weakSelf getModueStatus];
                };
                [self.navigationController pushViewController:inverterVC animated:YES];
            }
            
            
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
}


#pragma mark - JXCategoryListContentViewDelegate
/**
 实现 <JXCategoryListContentViewDelegate> 协议方法，返回该视图控制器所拥有的「视图」
 */
- (UIView *)listView {
    return self.view;
}
@end
